package com.ruoyi.bpm.service.oa.impl;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.ruoyi.bpm.api.task.BpmProcessInstanceApi;
import com.ruoyi.bpm.api.task.dto.BpmProcessInstanceCreateReqDTO;
import com.ruoyi.bpm.controller.admin.oa.vo.BpmOALeaveCreateReqVO;
import com.ruoyi.bpm.controller.admin.oa.vo.BpmOALeavePageReqVO;
import com.ruoyi.bpm.domain.oa.BpmOaLeave;
import com.ruoyi.bpm.enums.task.BpmTaskStatusEnum;
import com.ruoyi.bpm.mapper.oa.BpmOALeaveMapper;
import com.ruoyi.bpm.service.oa.BpmOALeaveService;
import com.ruoyi.bpm.utils.BeanUtils;
import com.ruoyi.common.orm.core.page.PageQuery;
import com.ruoyi.common.orm.core.page.TableDataInfo;
import com.ruoyi.common.orm.core.service.impl.BaseServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import java.util.HashMap;
import java.util.Map;

import static com.ruoyi.bpm.domain.oa.table.BpmOaLeaveTableDef.BPM_OA_LEAVE;
import static com.ruoyi.bpm.enums.ErrorCodeConstants.OA_LEAVE_NOT_EXISTS;
import static com.ruoyi.common.core.utils.ServiceExceptionUtil.exception;

/**
 * OA 请假申请 Service 实现类
 *
 * @author jason
 * @author 芋道源码
 */
@Service
@Validated
public class BpmOALeaveServiceImpl extends BaseServiceImpl<BpmOALeaveMapper, BpmOaLeave> implements BpmOALeaveService {

    /**
     * OA 请假对应的流程定义 KEY
     */
    public static final String PROCESS_KEY = "oa_leave";

    @Resource
    private BpmProcessInstanceApi processInstanceApi;

    @Override
    public QueryWrapper query() {
        return super.query().from(BPM_OA_LEAVE);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createLeave(Long userId, BpmOALeaveCreateReqVO createReqVO) {
        // 插入 OA 请假单
        long day = LocalDateTimeUtil.between(createReqVO.getStartTime(), createReqVO.getEndTime()).toDays();
        BpmOaLeave leave = BeanUtils.toBean(createReqVO, BpmOaLeave.class)
            .setUserId(userId).setDay(day).setStatus(BpmTaskStatusEnum.RUNNING.getStatus());
        mapper.insert(leave);

        // 发起 BPM 流程
        Map<String, Object> processInstanceVariables = new HashMap<>();
        processInstanceVariables.put("day", day);
        String processInstanceId = processInstanceApi.createProcessInstance(userId,
            new BpmProcessInstanceCreateReqDTO().setProcessDefinitionKey(PROCESS_KEY)
                .setVariables(processInstanceVariables).setBusinessKey(String.valueOf(leave.getId()))
                .setStartUserSelectAssignees(createReqVO.getStartUserSelectAssignees())).getCheckedData();

        // 将工作流的编号，更新到 OA 请假单中
        super.updateById(new BpmOaLeave().setId(leave.getId()).setProcessInstanceId(processInstanceId));
        return leave.getId();
    }

    @Override
    public void updateLeaveStatus(Long id, Integer status) {
        validateLeaveExists(id);
        super.updateById(new BpmOaLeave().setId(id).setStatus(status));
    }

    private void validateLeaveExists(Long id) {
        if (getLeave(id) == null) {
            throw exception(OA_LEAVE_NOT_EXISTS);
        }
    }

    @Override
    public BpmOaLeave getLeave(Long id) {
        return super.getById(id);
    }

    @Override
    public TableDataInfo<BpmOaLeave> getLeavePage(Long userId, BpmOALeavePageReqVO pageReqVO) {
        QueryWrapper queryWrapper = query()
            .where(BPM_OA_LEAVE.USER_ID.eq(userId, userId != null))
            .and(BPM_OA_LEAVE.STATUS.eq(pageReqVO.getStatus(), pageReqVO.getStatus() != null))
            .and(BPM_OA_LEAVE.TYPE.eq(pageReqVO.getType(), pageReqVO.getType() != null))
            .and(BPM_OA_LEAVE.REASON.like(pageReqVO.getReason(), StrUtil.isNotBlank(pageReqVO.getReason())))
            .and(BPM_OA_LEAVE.CREATE_TIME.between(pageReqVO.getCreateTime(), ArrayUtil.isNotEmpty(pageReqVO.getCreateTime())))
            .orderBy(BPM_OA_LEAVE.ID.desc());
        Page<BpmOaLeave> page = this.pageAs(PageQuery.build(), queryWrapper, BpmOaLeave.class);
        return TableDataInfo.build(page);
    }

}
